﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.IO;
using PPAP.Model;
using PPAP.BO;
using System.Data;

namespace PPAP.Web.Part
{
    public partial class PPAPTasksEdit : PageBase
    {
        PPInfoBO ppbo = new PPInfoBO();
        T_FileBO manager = new T_FileBO();
        string FJID;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["ID"] != null)
                {
                    GetPageData(Request.QueryString["ID"]);

                }
                else
                {
                    Session["FJID"] = DateTime.Now.ToString("yyyyMMddHHmmss");
                }
            }
        }

        /// <summary>
        /// 加载页面
        /// </summary>
        /// <param name="UserNo"></param>
        private void GetPageData(string id)
        {
            PPINFO pp = ppbo.GetModelByPPID(int.Parse(id));
            if (pp != null)
            {
                if (pp.STATUS > 1)
                {
                    divFankui.Visible = true;
                    qmfk.Visible = true;
                }

                //if (pp.STATUS == 6)
                //{
                //    DataTable dt1 = file.GetFileList(pp.SampleReportFJID, 0).Tables[0];
                //    if (dt1.Rows.Count > 0)
                //    {
                //        Repeater11.DataSource = dt1;
                //        Repeater11.DataBind();
                //        Div1.Visible = true;
                //    }
                //}
                divFankui.Visible = false;
                SupplierCode.Value = CurrentUser.Code;
                SupplierName.Value = CurrentUser.Name;
                BDNTPartNo.Value = pp.Bdntpartno;
                BDNTPartName.Value = pp.Bdntpartname;
                PartColor.Value = pp.Partcolor;
                SubmissionLevel.Value = pp.Submissionlevel;
                CreateDate.Value = pp.Createdate.ToString();
                CreateUser.Value = pp.Createuser;
                ELevel.Checked = pp.Elevel;
                QLevel.Checked = pp.Qlevel;
                PlannedISIRDate.Value = pp.PLANNEDISIRDATE.ToString();
                PPAPNo.Value = pp.PPAPNO;
                ECUHW.Value = pp.ECUHWVERSIONNO;
                ECUSW.Value = pp.ECUSWVERSIONNO;
                SamplingForm.Value = pp.SAMPLINGFORM;
                SamplingMode.Value = pp.SAMPLINGMODE;
                SamplingType.Value = pp.SAMPLINGTYPE;
                BNDTRevisionNo.Value = pp.BDNTREVISIONNO;
                BDNTRevisionStatus.Value = pp.BDNTREVISIONSTATUS;
                DeliveredPartsQ.Value = pp.DELIVEREDPARTSQ;
                ModificationScope.Value = pp.MODIFICATIONSCOPE;
                ExpressNo.Value = pp.EXPRESSNO;
                Plant.Value = pp.PLANT;
                Remarks.Value = pp.REMARKS;
                QMRemarks.Value = pp.QMREMARKS;
                FanKuiYiJian.Value = pp.TESTINGRESULT;
                if (pp.FJID != null && pp.FJID != "")
                    Session["FJID"] = pp.FJID;
                else
                    Session["FJID"] = DateTime.Now.ToString("yyyyMMddHHmmss");
                InitPage(pp.FJID);
            }

        }

        //窗体加载时绑定数据
        private void InitPage(string FJ)
        {
            FJID = FJ;
            DataCheck();//检查GUID是否为空,非常重要
            GufjID.Value = FJID;
            ShowData(FJID, 1, Repeater1); ShowData(FJID, 2, Repeater2);
            ShowData(FJID, 3, Repeater3); ShowData(FJID, 4, Repeater4);
            ShowData(FJID, 5, Repeater5); ShowData(FJID, 6, Repeater6);
            ShowData(FJID, 7, Repeater7); ShowData(FJID, 8, Repeater8);
            ShowData(FJID, 9, Repeater9); ShowData(FJID, 10, Repeater10);
        }
        //添加操作
        private void DataInfo(string F_FileID, string F_Filename, string path, int type, string url,string upby)
        {
            manager.InsertFile(F_FileID, F_Filename, path, type, url,"","",upby,"","","");
        }
        //判定附件id值
        private void DataCheck()
        {

        }
        #region 绑定已上传附件列表
        private void ShowData(string FileID, int Types, Repeater repeater)
        {
            DataSet ds = manager.GetFileList(FileID, Types);
            repeater.DataSource = ds;
            repeater.DataBind();
        }
        #endregion
        #region 上传附件操作
        private void UploadBind(FileUpload file, int type, Repeater repeater)
        {

            FJID = Session["FJID"].ToString();
            string FileName = file.FileName;
            if (!string.IsNullOrEmpty(FileName))
            {
                string extension = System.IO.Path.GetExtension(FileName);//获取文件类型后缀名
                if ((extension.ToLower() == ".pdf"))
                {
                    int fileSize = file.PostedFile.ContentLength;
                    if (fileSize == 0)
                    {
                        base.AlertMessage("上传失败,不存在此文件！");
                    }
                    else
                    {
                        if (true)//限制大小为1M
                        {
                            string FileNam_Time = "";
                            int FileIndex = FileName.LastIndexOf("\\");
                            string FName = FileName.Substring(FileIndex + 1);
                            FileNam_Time = FName;//日期和名称组合
                            string path = HttpContext.Current.Request.MapPath("../FileUpload/QYRD/" + base.CurrentUser.Name + "/");
                            string url = "../FileUpload/QYRD/" + CurrentUser.Name + "/new" + FileNam_Time;
                            DirectoryInfo upDir = new DirectoryInfo(path);
                            if (!upDir.Exists)
                            {
                                upDir.Create();
                            }
                            file.SaveAs(path + FileNam_Time);
                            ///加水印
                            string source = path + FileNam_Time; //模板路径
                            string output = path + "new" + FileNam_Time; //导出水印背景后的PDF
                            string watermark = "../FileUpload/ShuiYin/" + CurrentUser.Id + ".png";   // 水印图片
                            DirectoryInfo upDir2 = new DirectoryInfo(HttpContext.Current.Request.MapPath("../FileUpload/ShuiYin/"));
                            if (!upDir2.Exists)
                            {
                                upDir2.Create();
                            }
                            if (File.Exists(watermark)) //如果存在，则删除重新生成
                            {
                                File.Delete(watermark);
                            }
                            AddShuiYin(base.CurrentUser.Name + "(" + base.CurrentUser.Id + ")" + DateTime.Now.ToString("yyyyMMdd HHmmss"), watermark);
                            bool isSurrcess = PDFWatermark(source, output, MapPath(watermark), 10, 10);
                            if (isSurrcess)
                                File.Delete(source); //删除原文件
                            //加水印
                            DataInfo(FJID, FileNam_Time, path + "new", type, url,CurrentUser.Id);
                            ShowData(FJID, type, repeater);
                        }
                    }
                }
                else
                {
                    AlertMessage("不能上传此类型的文件");
                }
            }
            else
            {
                AlertMessage("请选择附件,不能为空！");
            }
        }

        /// <summary>
        /// PDF添加水印
        /// </summary>
        /// <param name="inputfilepath"></param>
        /// <param name="outputfilepath"></param>
        /// <param name="ModelPicName"></param>
        /// <param name="top"></param>
        /// <param name="left"></param>
        /// <returns></returns>
        public bool PDFWatermark(string inputfilepath, string outputfilepath, string ModelPicName, float top, float left)
        {
            PdfReader pdfReader = null;
            PdfStamper pdfStamper = null;
            try
            {
                pdfReader = new PdfReader(inputfilepath);

                int numberOfPages = pdfReader.NumberOfPages;

                iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);

                float width = psize.Width;

                float height = psize.Height;

                pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create));

                PdfContentByte waterMarkContent;

                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(ModelPicName);

                // image.Width = 200;
                // image.Height = 50;

                image.GrayFill = 20;//透明度，灰色填充
                left = width - image.Width + left;
                //top = height - image.Height - top;
                image.SetAbsolutePosition(left, top);

                //每一页加水印,也可以设置某一页加水印 
                for (int i = 1; i <= numberOfPages; i++)
                {
                    waterMarkContent = pdfStamper.GetUnderContent(i);

                    waterMarkContent.AddImage(image);
                }
                return true;
            }
            catch (Exception ex)
            {
                AlertMessage(ex.Message.Trim());
                return false;
            }
            finally
            {

                if (pdfStamper != null)
                    pdfStamper.Close();

                if (pdfReader != null)
                    pdfReader.Close();
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            UploadBind(FileUpload1, 1, Repeater1);
            this.Page.RegisterStartupScript("", "<script>setTab03Syn(2);document.getElementById('bg').className='xixi2'</script>");
        }
        protected void Button2_Click(object sender, EventArgs e)
        {
            UploadBind(FileUpload2, 2, Repeater2);
            this.Page.RegisterStartupScript("", "<script>setTab03Syn(2);document.getElementById('bg').className='xixi2'</script>");
        }
        protected void Button3_Click(object sender, EventArgs e)
        {
            UploadBind(FileUpload3, 3, Repeater3);
            this.Page.RegisterStartupScript("", "<script>setTab03Syn(2);document.getElementById('bg').className='xixi2'</script>");
        }
        protected void Button4_Click(object sender, EventArgs e)
        {
            UploadBind(FileUpload4, 4, Repeater4);
            this.Page.RegisterStartupScript("", "<script>setTab03Syn(2);document.getElementById('bg').className='xixi2'</script>");
        }
        protected void Button5_Click(object sender, EventArgs e)
        {
            UploadBind(FileUpload5, 5, Repeater5);
            this.Page.RegisterStartupScript("", "<script>setTab03Syn(2);document.getElementById('bg').className='xixi2'</script>");
        }
        protected void Button6_Click(object sender, EventArgs e)
        {
            UploadBind(FileUpload6, 6, Repeater6);
            this.Page.RegisterStartupScript("", "<script>setTab03Syn(2);document.getElementById('bg').className='xixi2'</script>");
        }
        protected void Button7_Click(object sender, EventArgs e)
        {
            UploadBind(FileUpload7, 7, Repeater7);
            this.Page.RegisterStartupScript("", "<script>setTab03Syn(2);document.getElementById('bg').className='xixi2'</script>");
        }
        protected void Button8_Click(object sender, EventArgs e)
        {
            UploadBind(FileUpload8, 8, Repeater8);
            this.Page.RegisterStartupScript("", "<script>setTab03Syn(2);document.getElementById('bg').className='xixi2'</script>");
        }
        protected void Button9_Click(object sender, EventArgs e)
        {
            UploadBind(FileUpload9, 9, Repeater9);
            this.Page.RegisterStartupScript("", "<script>setTab03Syn(2);document.getElementById('bg').className='xixi2'</script>");
        }
        protected void Button10_Click(object sender, EventArgs e)
        {
            UploadBind(FileUpload10, 10, Repeater10);
            this.Page.RegisterStartupScript("", "<script>setTab03Syn(2);document.getElementById('bg').className='xixi2'</script>");
        }
        //protected void Button11_Click(object sender, EventArgs e)
        //{
        //    UploadBind(FileUpload11, 11, Repeater11);
        //}
        #endregion

        #region  删除附件操作
        protected void lbtnDelete_Init(object sender, EventArgs e)
        {
            (sender as LinkButton).Attributes.Add("onclick", string.Format("javascript:return confirm('{0}');", "确定要删除当前记录吗?\\n本操作不可恢复!"));
        }
        //删除
        protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "delete")
            {
                int ContID = Convert.ToInt32(e.CommandArgument.ToString());
                try
                {
                    DataSet ds = manager.Getpath(ContID);
                    string path = ds.Tables[0].Rows[0]["F_Detail"].ToString();

                    if (manager.DeleteFile(ContID.ToString()))
                    {
                        File.Delete(path);
                        ShowData(Session["FJID"].ToString(), 1, Repeater1);
                    }

                }
                catch (Exception)
                {

                    throw;
                }
            }
            this.Page.RegisterStartupScript("", "<script>setTab03Syn(2);document.getElementById('bg').className='xixi2'</script>");
        }
        protected void Repeater2_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "delete")
            {
                int ContID = Convert.ToInt32(e.CommandArgument.ToString());
                try
                {
                    manager.DeleteFile(ContID.ToString());
                    ShowData(Session["FJID"].ToString(), 2, Repeater2);
                }
                catch (Exception)
                {

                    throw;
                }
            }

            this.Page.RegisterStartupScript("", "<script>setTab03Syn(2);document.getElementById('bg').className='xixi2'</script>");
        }
        protected void Repeater3_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "delete")
            {
                int ContID = Convert.ToInt32(e.CommandArgument.ToString());
                try
                {
                    manager.DeleteFile(ContID.ToString());
                    ShowData(Session["FJID"].ToString(), 3, Repeater3);
                }
                catch (Exception)
                {

                    throw;
                }
            }
            this.Page.RegisterStartupScript("", "<script>setTab03Syn(2);document.getElementById('bg').className='xixi2'</script>");
        }
        protected void Repeater4_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "delete")
            {
                int ContID = Convert.ToInt32(e.CommandArgument.ToString());
                try
                {
                    manager.DeleteFile(ContID.ToString());
                    ShowData(Session["FJID"].ToString(), 4, Repeater4);
                }
                catch (Exception)
                {

                    throw;
                }
            }
            this.Page.RegisterStartupScript("", "<script>setTab03Syn(2);document.getElementById('bg').className='xixi2'</script>");
        }
        protected void Repeater5_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "delete")
            {
                int ContID = Convert.ToInt32(e.CommandArgument.ToString());
                try
                {
                    manager.DeleteFile(ContID.ToString());
                    ShowData(Session["FJID"].ToString(), 4, Repeater4);
                }
                catch (Exception)
                {

                    throw;
                }
            }
            this.Page.RegisterStartupScript("", "<script>setTab03Syn(2);document.getElementById('bg').className='xixi2'</script>");
        }
        protected void Repeater6_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "delete")
            {
                int ContID = Convert.ToInt32(e.CommandArgument.ToString());
                try
                {
                    manager.DeleteFile(ContID.ToString());
                    ShowData(Session["FJID"].ToString(), 6, Repeater6);
                }
                catch (Exception)
                {

                    throw;
                }
            }
            this.Page.RegisterStartupScript("", "<script>setTab03Syn(2);document.getElementById('bg').className='xixi2'</script>");
        }


        protected void Repeater7_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "delete")
            {
                int ContID = Convert.ToInt32(e.CommandArgument.ToString());
                try
                {
                    DataSet ds = manager.Getpath(ContID);
                    string path = ds.Tables[0].Rows[0]["F_Detail"].ToString();

                    if (manager.DeleteFile(ContID.ToString()))
                    {
                        File.Delete(path);
                        ShowData(Session["FJID"].ToString(), 7, Repeater7);
                    }

                }
                catch (Exception)
                {

                    throw;
                }
            }
            this.Page.RegisterStartupScript("", "<script>setTab03Syn(2);document.getElementById('bg').className='xixi2'</script>");
        }
        protected void Repeater8_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "delete")
            {
                int ContID = Convert.ToInt32(e.CommandArgument.ToString());
                try
                {
                    manager.DeleteFile(ContID.ToString());
                    ShowData(Session["FJID"].ToString(), 8, Repeater8);
                }
                catch (Exception)
                {

                    throw;
                }
            }
            this.Page.RegisterStartupScript("", "<script>setTab03Syn(2);document.getElementById('bg').className='xixi2'</script>");
        }
        protected void Repeater9_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "delete")
            {
                int ContID = Convert.ToInt32(e.CommandArgument.ToString());
                try
                {
                    manager.DeleteFile(ContID.ToString());
                    ShowData(Session["FJID"].ToString(), 9, Repeater9);
                }
                catch (Exception)
                {

                    throw;
                }
            }
            this.Page.RegisterStartupScript("", "<script>setTab03Syn(2);document.getElementById('bg').className='xixi2'</script>");
        }
        protected void Repeater10_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "delete")
            {
                int ContID = Convert.ToInt32(e.CommandArgument.ToString());
                try
                {
                    manager.DeleteFile(ContID.ToString());
                    ShowData(Session["FJID"].ToString(), 10, Repeater10);
                }
                catch (Exception)
                {

                    throw;
                }
            }
            this.Page.RegisterStartupScript("", "<script>setTab03Syn(2);document.getElementById('bg').className='xixi2'</script>");
        }
        //protected void Repeater11_ItemCommand(object source, RepeaterCommandEventArgs e)
        //{
        //    if (e.CommandName == "delete")
        //    {
        //        int ContID = Convert.ToInt32(e.CommandArgument.ToString());
        //        try
        //        {
        //            manager.DeleteFile(ContID.ToString());
        //            ShowData(FJID, 11, Repeater11);
        //        }
        //        catch (Exception)
        //        {

        //            throw;
        //        }
        //    }
        //}
        #endregion
        protected void BtnSaveClose_Click(object sender, EventArgs e)
        {
            Addrending(1);
        }
        protected void BtnSaveTemp_Click(object sender, EventArgs e)
        {
            Addrending(0);
        }


        protected void Addrending(int isssve)
        {
            PPINFO pp = ppbo.GetModelByPPID(int.Parse(Request.QueryString["ID"].ToString()));

            pp.Bdntpartname = BDNTPartName.Value;
            pp.Bdntpartno = BDNTPartNo.Value;
            pp.BDNTREVISIONNO = BDNTPartNo.Value;
            pp.BDNTREVISIONSTATUS = BDNTRevisionStatus.Value;
            pp.DELIVEREDPARTSQ = DeliveredPartsQ.Value;
            pp.ECUHWVERSIONNO = ECUHW.Value;
            pp.ECUSWVERSIONNO = ECUSW.Value;
            pp.EXPRESSNO = ExpressNo.Value;
            pp.MODIFICATIONSCOPE = ModificationScope.Value;
            pp.PLANT = Plant.Value;
            pp.PPAPNO = PPAPNo.Value;
            pp.REMARKS = Remarks.Value;
            pp.SAMPLINGFORM = SamplingForm.Value;
            pp.SAMPLINGMODE = SamplingMode.Value;
            pp.SAMPLINGTYPE = SamplingType.Value;
            pp.STATUS = isssve;
            pp.SUBMITTIME = DateTime.Now;
            //ColorDecision="",
            //CostCharge="",
            pp.ENDTIME = DateTime.Now;
            //FinalDecision="",
            //LogFile="",
            //PartRelatedResult="",
            pp.PLANNEDISIRDATE = DateTime.Now;
            //ProcessRelatedResult="",
            //QMInspector="",
            //SampleReportAuthor="",
            pp.STARTTIME = DateTime.Now;
            //SSA="",
            //TestingPerson="",TestingResult="",
            pp.TESTINGTIME = DateTime.Now;


            FJID = Session["FJID"].ToString();
            pp.FJID = FJID;
            //};


            //if (Request.QueryString["ID"] == null)
            //{

            //    if (ppbo.Add(pp) > 0)
            //    {
            //        AlertReflashOpener("保存成功");

            //    }
            //}
            //else
            //{
                pp.ID = int.Parse(Request.QueryString["ID"].ToString());
                if (ppbo.Update(pp) > 0)
                {
                    AlertReflashOpener("保存成功");
                }
            //}

        }
        protected void BtnCheck_Click(object sender, EventArgs e)
        {

        }
        protected void BtnRetu_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 生成水印图片
        /// </summary>
        /// <param name="Name"></param>
        /// <param name="Path"></param>
        private void AddShuiYin(string Name, string Path)
        {
            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(260, 20);
            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);
            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(bitmap, new System.Drawing.Rectangle(0, 0, 260, 20),

            new System.Drawing.Rectangle(0, 0, 0, 0),

            System.Drawing.GraphicsUnit.Pixel);
            System.Drawing.Font f = new System.Drawing.Font("宋体", 12);
            System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.Black);
            g.DrawString(Name, f, b, 2, 2);
            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(MapPath(Path), System.Drawing.Imaging.ImageFormat.Png);
            }
            catch (System.Exception ex)
            {
                AlertMessage(ex.Message.ToString());
            }
            finally
            {
                bitmap.Dispose();
                //bitmap.Dispose();
                g.Dispose();
            }
        }
    }
}